<template>
  <section>
    <div class="filter-container">
        <common-input type="number" @keyup.enter.native="handleFilter" class="w100" placeholder="商品编号" v-model="listQuery.productNo" />
        <common-input @keyup.enter.native="handleFilter" class="w100 ml10" placeholder="商品名称" v-model="listQuery.keyword" />
        <common-input @keyup.enter.native="handleFilter" class="w100 ml10" placeholder="供应商" v-model="listQuery.agency" />
        <el-select class="ml10" @change="getCateList(false)" size="mini" v-model="listQuery.parentCateId" placeholder="一级分类">
            <el-option
                    v-for="item in parentCateList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
            </el-option>
        </el-select>
        <el-select size="mini" class="ml10" v-model="listQuery.cateId" placeholder="二级分类">
            <el-option
                    v-for="item in cateList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
            </el-option>
        </el-select>
        <el-button size="mini" class="ml10" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>
    <el-tabs size="mini" :before-leave='leaveTab' v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="待审核" name="2"></el-tab-pane>
      <el-tab-pane label="被驳回" name="4"></el-tab-pane>
    </el-tabs>
    <el-alert
            v-if="ids&&ids.length>0"
            show-icon>
        <template slot="title">
            <span>已选择 {{ids.length}} 项</span> 
            <el-button @click="clear()" type="text">清空</el-button>
            <el-button v-if="activeName=='2'" @click="doCheck()" type="text">批量审核</el-button>
            <el-button v-if="activeName=='2'" @click="doWholesale()" type="text">批量批发价</el-button>
            <el-button @click="doDelete()" type="text">批量删除</el-button>
        </template>
    </el-alert>
    <el-table ref="dataTable" :data="list" :height="tableHeight"
                        @sort-change="tblSort"
                        @selection-change="selectChange"
                style="width: 100%">
            <el-table-column
                    fixed
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column align="left" label="商品编号" >
                <template slot-scope="scope">
                    <span>{{scope.row.id}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="" width="140">
                <template slot-scope="scope">
                    <span><img :src="scope.row.listImgUrl" style="width:80px;cursor:pointer;" @click="viewPic(scope.row)" /></span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="商品">
                <template slot-scope="scope">
                    <span>{{scope.row.title}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="供应商" >
                <template slot-scope="scope">
                    <span>{{scope.row.agencyName}}</span>
                </template>
            </el-table-column>
            <el-table-column align="right" width="100" label="供货价" sortable="custom" prop="min_supply_price">
                <template slot-scope="scope">
                    <span>￥{{scope.row.minSupplyPrice}}</span>
                </template>
            </el-table-column>
            <el-table-column align="right" width="100" label="批发价" sortable="custom" prop="min_wholesale_price">
                <template slot-scope="scope">
                    <span>￥{{scope.row.minWholesalePrice}}</span>
                </template>
            </el-table-column>
            <el-table-column width="100" align="right" label="物流成本" sortable="custom" prop="freight_price">
                <template slot-scope="scope">
                    <span>￥{{scope.row.freightPrice}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="商品类目" >
                <template slot-scope="scope">
                    <span>{{scope.row.cateName}}</span>
                </template>
            </el-table-column>
            <!-- <el-table-column align="left" label="状态" >
                <template slot-scope="scope">
                    <span>{{scope.row.statusText}}</span>
                </template>
            </el-table-column> -->
            <el-table-column align="center" label="提交时间" width="180" sortable="custom" prop="created_at">
                <template slot-scope="scope">
                    <span>{{scope.row.createdAt}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="审核时间" width="180" sortable="custom" prop="check_at">
                <template slot-scope="scope">
                    <span>{{scope.row.checkAt}}</span>
                    <p v-if="scope.row.auditStatus==3" style="color:red;">{{ scope.row.checkNote }}</p>
                </template>
            </el-table-column>
            <el-table-column
                    fixed="right" align="center" label="操作" width="250">
                <template slot-scope="scope">
                    <span>
                        <el-button type="text" @click="handleDetail(scope.row)">查看</el-button>
                        <el-button v-if="scope.row.canCheck==1" type="text" @click="handleCheck(scope.row)">审核</el-button>
                        <el-button v-if="scope.row.canCheck==1" type="text" @click="handleWholesale(scope.row)">批发价</el-button>
                        <el-button v-if="scope.row.canEdit==1" type="text" @click="handleUpdate(scope.row)">编辑</el-button>
                        <el-button v-if="scope.row.canDelete==1" type="text" @click="handleDelete(scope.row)">删除</el-button>
                    </span>
                </template>
            </el-table-column>
    </el-table>
        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNum" :page-sizes="[20,30, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
        </div>

    <el-dialog title="商品审核" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="500px" @close="dialogClose">
        <el-form :model="form" ref="form" label-width="150px">
            <el-form-item label="操作类型" prop="status">
                <el-radio-group v-model="form.status">
                    <el-radio :label="1">通过</el-radio>
                    <el-radio :label="2">驳回</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="note">
                <common-input type="textarea" :autosize="{ minRows: 3, maxRows: 5}" placeholder="拒绝审核时必填" maxlength="100" v-model="form.note" />
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button size="mini" @click="cancel('form')">取消</el-button>
            <el-button :loading="checkLoading" size="mini" type="primary" @click="check('form')">确定</el-button>
        </div>
    </el-dialog>

    <el-dialog title="设置批发价" :visible.sync="dialogForm2Visible" :close-on-click-modal="false" width="500px" @close="dialogClose2">
        <el-form :model="form2" ref="form2" label-width="150px">
            <el-form-item label="上浮比例" prop="rate">
                <el-input type="number" v-model.number="form2.rate" size="mini" placeholder="上浮比例"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button size="mini" @click="dialogForm2Visible=false">取消</el-button>
            <el-button :loading="checkLoading2" size="mini" type="primary" @click="check2('form2')">确定</el-button>
        </div>
    </el-dialog>
  </section>
</template>

<script>
    import {
        product_list,
        product_delete,
        product_submit,
        product_check,
        product_wholesale
    } from '../../api/product';
    import {
        agency_categories
    } from '../../api/agency';
    import Viewer from 'viewerjs';
    import 'viewerjs/dist/viewer.css';
    export default {
        components: {
        },
        data() {
            return {
                ids: [],
                tableHeight: 200,
                viewerId: null,
                cateList: [],
                parentCateList:[],
                list: null,
                listLoading: true,
                listQuery: {
                    pageNum: this.$route.query.pageNum || 1,
                    pageSize: this.$route.query.pageSize || 20,
                    agency: this.$route.query.agency,
                    keyword: this.$route.query.keyword,
                    auditStatus: '2',
                    orderCol: "",
                    orderAsc: "",
                    cateId: this.$route.query.cateId,
                    parentCateId: this.$route.query.parentCateId,
                    productNo: this.$route.query.productNo,
                },
                total: null,
                activeName: '2',
                currentId: 0,
                dialogFormVisible: false,
                dialogForm2Visible: false,
                form: {
                    status: 1,
                    note: undefined,
                    id: [],
                },
                form2: {
                    rate: undefined,
                    id: [],
                },
                checkLoading: false,
                checkLoading2: false,
            }
        },
        mounted() {
            const that = this

            window.onresize = () => {

                return (() => {

                    that._getTableHeight()

                })()
            }
        },
        created() {
            this._getTableHeight();
            this.getParentCateList();
            this.getList();
        },
        methods: {
            clear() {
                this.$refs.dataTable.clearSelection();
            },
            selectChange(selection) {
                this.ids = [];
                if(selection && selection.length > 0) {
                    selection.forEach((item)=>{
                        this.ids.push(item.id)
                    })
                }
                // console.log(this.ids)
            },
            _getTableHeight() {
                this.tableHeight = window.innerHeight - 250
            },
            getList() {
                this.listLoading = true;
                product_list(this.listQuery).then(response => {
                    this.list = response.data.list;
                    this.total = response.data.total;
                    this.listLoading = false;
                })
            },
            getParentCateList() {
                agency_categories(0).then((res)=>{
                    this.parentCateList = res.data;
                    this.cateList = []
                }).catch((err)=>{
                    this.parentCateList = []
                    this.cateList = []
                });
            },
            getCateList() {
                this.listQuery.cateId = undefined;
                agency_categories(this.listQuery.parentCateId).then((res)=>{
                    this.cateList = res.data;
                }).catch((err)=>{
                    this.cateList = []
                });
            },
            handleFilter() {
                this.listQuery.pageNum = 1;
                this.getList();
            },
            handleSizeChange(val) {
                this.listQuery.pageSize = val;
                this.getList();
            },
            viewPic(row) {
                if(row.imgUrls) {
                    let all_pic = row.imgUrls.split(",");
                    $("#pic_viewer").html("");
                    if(all_pic && all_pic.length > 0) {
                        all_pic.forEach((item, idx)=>{
                            var str  = '<li style="width:100%;">';
                            str += '<img rel-src="' + item + '" src="' + item + '">';
                            str += '</li>';
                            $("#pic_viewer").append(str);
                        })
                    }
                    this.viewerId && this.viewerId.destroy()
                    this.viewerId = new Viewer(document.getElementById('pic_viewer'));
                    $('#pic_viewer').find("img").eq(0).trigger("click")
                }
            },
            handleCurrentChange(val) {
                this.listQuery.page = val;
                this.getList();
            },
            handleClick(tab, event) {
                this.listQuery.auditStatus = this.activeName;
                this.handleFilter();
            // console.log(this.activeName)
            },
            leaveTab(activeName, oldActiveName) {
            // console.log(activeName)
            // return false;
            },
            handleUpdate(row) {
                let url = "/goods_edit?id=" + row.id 
                    + "&from=goods_check"
                    + "&pageSize=" + encodeURIComponent(this.listQuery.pageSize)
                    + "&pageNum=" + encodeURIComponent(this.listQuery.pageNum);
                if(this.listQuery.keyword) {
                    url += "&keyword=" + encodeURIComponent(this.listQuery.keyword);
                }
                if(this.listQuery.productNo) {
                    url += "&productNo=" + encodeURIComponent(this.listQuery.productNo);
                }
                if(this.listQuery.agency) {
                    url += "&agency=" + encodeURIComponent(this.listQuery.agency);
                }
                if(this.listQuery.parentCateId) {
                    url += "&parentCateId=" + this.listQuery.parentCateId;
                }
                if(this.listQuery.cateId) {
                    url += "&cateId=" + this.listQuery.cateId;
                }
                this.$router.push(url)
                // this.$router.push("/goods_edit?id=" + row.id + "&from=" + encodeURIComponent(this.$router.currentRoute.name)) 
            },
            handleSubmit(row) {
                this.$confirm('此操作将提交商品审核, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        product_submit(row.id)
                            .then(() => {
                                this.$message.success("商品已提交审核");
                                this.getList();
                            });
                    }).catch(()=>{});
                
            },
            handleDelete(row) {
                this.doDelete([row.id])
            },
            doDelete(ids) {
                if(!ids || ids.length < 1) {
                    ids = this.ids;
                }
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        product_delete(ids)
                            .then(() => {
                                this.$message.success("商品删除成功");
                                this.getList();
                            });
                    }).catch(()=>{});
            },
            doCheck(ids) {
                if(!ids || ids.length < 1) {
                    ids = this.ids;
                }
                this.form.id = ids;
                this.form.status = 1;
                this.form.note = "";

                this.dialogFormVisible = true;
            },
            handleCheck(row) {
                this.doCheck([row.id])
            },
            doWholesale(ids) {
                if(!ids || ids.length < 1) {
                    ids = this.ids;
                }
                this.form2.id = ids;
                this.form2.rate = undefined;

                this.dialogForm2Visible = true;
            },
            handleWholesale(row) {
                this.doWholesale([row.id])
            },
            handleDetail(row) {
                let {href} = this.$router.resolve({path: '/goods_detail?id=' + row.id});
                window.open(href, '_blank');
            },
            dialogClose() {
                this.$refs.form.resetFields();
            },
            dialogClose2() {
                this.$refs.form2.resetFields();
            },
            cancel(formName) {
                this.dialogFormVisible = false;
                this.$refs[formName].resetFields();
            },
            check(formName) {
                this.form.note = $.trim(this.form.note)

                // console.log(this.form)
                if(this.form.status == 2) {
                    if(this.form.note.length < 1) {
                        this.$message.error("拒绝审核时备注必填");
                        return;
                    }
                }
                this.checkLoading = true;
                product_check(this.form).then((res)=>{
                    this.checkLoading = false;
                    this.$message.success("商品已审核");
                    this.dialogFormVisible = false;
                    this.getList();
                }).catch((err)=>{
                    this.checkLoading = false;

                })
            },
            check2(formName) {
                // this.form2.rate = parseFloat($.trim(this.form2.rate)) || 0;
                // if(this.form2.rate <= 0) {
                //     this.$message.error("请设置上浮比例");
                //     return;
                // }
                this.checkLoading2 = true;
                product_wholesale(this.form2).then((res)=>{
                    this.checkLoading2 = false;
                    this.$message.success("商品已设置批发价");
                    this.dialogForm2Visible = false;
                    this.getList();
                }).catch((err)=>{
                    this.checkLoading2 = false;
                })
            },
            tblSort(d) {
                this.listQuery.orderCol = d.prop;
                this.listQuery.orderAsc = d.order;

                this.handleFilter();
            }
        }
    };
</script>
<style lang="scss" scoped>
</style>
